/*
 * @Author: qingyuanyang
 * @Date: 2023-09-19 11:05:18
 * @LastEditors: qingyuanyang
 * @LastEditTime: 2023-10-12 13:49:27
 * @FilePath: /utilization-platform/src/pages/VisualizationAnalysis/DeviceStatus/components/changeChart/index.tsx
 * @Description: 设备异常趋势分析图
 */

import { useEffect, useRef, useState } from 'react';
import { AutoComplete, Button, Form, Input, Spin } from 'antd';
import Card from '@/components/Card';
import Chart from '@/components/Chart';
import BeforefixSelect from '@/components/BeforefixSelect';
import { graphic } from '@/utils/echartConfig';
import type { ChartRef } from '@/components/Chart';

import style from './index.module.scss';
import { dimensionTypeOptions, Label } from '../../type';
import Icon from '@/components/SvgIcon';
import { useRequest } from 'ahooks';
import {
  ExceptionStatus,
  getDevExceptionStatusTrend,
} from '@/api/deviceStatus';
import MyRangePicker from '@/components/RangePicker';
import { queryDeviceByCode } from '@/api/device';
import { disabledDateHasCurrent } from '@/utils/antMixin';
import dayjs from 'dayjs';
const premonth = new Date().getMonth() + 1 - 3; //最近4个季度
const allDefaultDate = {
  day: [
    dayjs(dayjs().add(-31, 'd'), 'YYYY-MM-DD'),
    dayjs(dayjs().add(0, 'd'), 'YYYY-MM-DD'),
  ],
  month: [
    dayjs(dayjs().add(-12, 'month'), 'YYYY-MM'),
    dayjs(dayjs().add(0, 'month'), 'YYYY-MM'),
  ],
  quarter: [
    dayjs(dayjs().add(-premonth, 'month'), 'YYYY-MM'),
    dayjs(dayjs().add(0, 'month'), 'YYYY-MM'),
  ],
  year: [
    dayjs(dayjs().add(-2, 'y'), 'YYYY'),
    dayjs(dayjs().add(0, 'y'), 'YYYY'),
  ],
};

const ChangeChart: React.FC = () => {
  const chartRef = useRef<ChartRef>(null);
  //设备编码
  const [xData, setXData] = useState([]);
  const [yData, setYData] = useState([]);
  const [type, setType] = useState<Label>(dimensionTypeOptions[0]);
  const [defaultDate, setDefaultDate] = useState<any>(allDefaultDate.day); //默认日期

  const [params, setParams] = useState<ExceptionStatus>({
    workStatus: 0,
    startTime: defaultDate?.[0].format('YYYY-MM-DD') || null,
    endTime: defaultDate?.[1].format('YYYY-MM-DD') || null,
  });
  const rangeRef: any = useRef(null);
  const [form] = Form.useForm();
  const [keyword, setKeyword] = useState<string>();
  const [deviceOptions, setDeviceOptions] = useState<any[]>([]);

  useEffect(() => {
    form.setFieldValue('workStatus', 0);
  }, []);
  // 辅助查询设备编号
  useRequest(() => queryDeviceByCode({ searchKey: keyword }), {
    debounceWait: 500,
    refreshDeps: [keyword],
    onSuccess: res => {
      const options = res.data.map((r: any) => ({
        ...r,
        label: r.deviceCode,
        value: r.deviceCode,
      }));
      setDeviceOptions(options);
    },
  });

  //查询异常趋势数据
  const { run: getListData, loading } = useRequest(
    () =>
      getDevExceptionStatusTrend({
        ...params,
        ...form.getFieldsValue(),
        timeDimensionType:
          rangeRef.current.picker === 'date' ? 'day' : rangeRef.current.picker,
      }),
    {
      manual: true,
      debounceWait: 300,
      onSuccess: ({ data }) => {
        const timeData: any = [];
        const valueData: any = [];

        data.forEach((item: any) => {
          timeData.push(item.statisticalItem);

          valueData.push(
            Number(((item.statisticalValue as number) / 3600).toFixed(1))
          );
        });
        setXData(timeData);
        setYData(valueData);
      },
    }
  );

  const option: any = {
    tooltip: {
      trigger: 'axis',

      axisPointer: {
        type: 'shadow',
      },
      formatter: (params: any) => {
        let name = `<span style="color: #191B27; font-weight: bold">${params[0].name}</span>`;
        for (let i = 0; i < params.length; i++) {
          name += `<br />${params[i].marker}${type?.label}<span style="color: #191B27; font-weight: bold;margin-left: 10px">${params[i].value} </span>`;
        }
        return name;
      },
    },

    grid: {
      borderWidth: 0,
      left: 55,
      right: 5,
      top: 65,
      bottom: 60,
    },
    xAxis: [
      {
        type: 'category',
        data: xData,
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '小时',
        nameTextStyle: {
          fontSize: 12,
          color: 'rgba(0, 0, 0, 0.5)',
          padding: [0, 8, 5, 0],
          align: 'right',
        },
        splitLine: {
          lineStyle: {
            color: ['#EBEDF0'],
          },
        },
      },
    ],
    dataZoom: [
      {
        type: 'slider',
        show: xData.length > 10,
        height: 10,
        xAxisIndex: [0],
        bottom: 10,
        start: 0,
        end: 100,
        handleIcon:
          'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
        handleSize: '100%',
        textStyle: {
          color: '#fff',
        },
        borderColor: '#f2f3f7',
        fillerColor: '#e9e8ed',
        moveHandleStyle: {
          color: 'rgba(144, 147, 153, 0.3)',
        },
      },
    ],
    series: [
      {
        // name: '工作时间',
        type: 'line',
        barMaxWidth: 35,
        barGap: 0,
        itemStyle: {
          color: '#4E6FF5',
        },
        data: yData,
        showBackground: true,
        backgroundStyle: { color: 'red' },
      },
    ],
  };

  //下拉选择
  const onChange = (_: number, item: any) => {
    setType(item);
    form.setFieldValue('workStatus', item.value);
  };
  //时间变化
  const dateChange = (_: any, dateStr: any) => {
    if (!dateStr[0] && !dateStr[1]) {
      setDefaultDate(null);
      setParams({
        ...params,
        startTime: undefined,
        endTime: undefined,
      });
    } else {
      setParams({
        ...params,
        startTime: dateStr[0],
        endTime: dateStr[1],
      });
    }
  };
  //获取当前季度
  const getQuarterByMonth = (month: number) => {
    if (month >= 1 && month <= 3) {
      return 1;
    } else if (month >= 4 && month <= 6) {
      return 2;
    } else if (month >= 7 && month <= 9) {
      return 3;
    } else {
      return 4;
    }
  };

  //切换日期tab
  const pickerTypeChange = (e: any) => {
    getDateParams(e);
  };

  //获取日期参数
  const getDateParams = (e: any) => {
    switch (e) {
      case 'date':
        setDefaultDate(allDefaultDate.day);
        setParams({
          ...params,
          startTime: allDefaultDate.day[0].format('YYYY-MM-DD'),
          endTime: allDefaultDate.day[1].format('YYYY-MM-DD'),
        });

        break;
      case 'month':
        setDefaultDate(allDefaultDate.month);
        setParams({
          ...params,
          startTime: allDefaultDate.month[0].format('YYYY-MM'),
          endTime: allDefaultDate.month[1].format('YYYY-MM'),
        });

        break;
      case 'quarter':
        setDefaultDate(allDefaultDate.quarter);
        setParams({
          ...params,
          startTime:
            allDefaultDate.quarter[0].format('YYYY') +
            '-Q' +
            getQuarterByMonth(allDefaultDate.quarter[0].month() + 1),
          endTime:
            allDefaultDate.quarter[1].format('YYYY') +
            '-Q' +
            getQuarterByMonth(allDefaultDate.quarter[1].month() + 1),
        });
        break;
      case 'year':
        setDefaultDate(allDefaultDate.year);
        setParams({
          ...params,
          startTime: allDefaultDate.year[0].format('YYYY'),
          endTime: allDefaultDate.year[1].format('YYYY'),
        });
        break;
    }
  };

  return (
    <Card title="设备异常变化趋势">
      <div className={style.searchArea}>
        <Form name="filterForm" form={form} layout="inline" autoComplete="off">
          <Form.Item name="deviceCode" label="">
            <AutoComplete
              children={
                <Input
                  // style={{ width: 300 }}
                  prefix={
                    <Icon name="icon-search" className={style.iconStyle} />
                  }
                  placeholder="请输入设备编号进行搜索"
                  onChange={e => {
                    setKeyword(e.target.value);
                  }}
                />
              }
              style={{ width: 300 }}
              options={deviceOptions}
            />
          </Form.Item>
          <Form.Item name="workStatus" label="">
            <BeforefixSelect
              beforefix="异常维度"
              options={dimensionTypeOptions}
              defaultValue={'累计关机时长'}
              onChange={onChange}
              style={{ width: 150 }}
            />
          </Form.Item>

          <MyRangePicker
            ref={rangeRef}
            dateChange={dateChange}
            defaultDate={defaultDate}
            disableDateRef={disabledDateHasCurrent}
            typeChange={pickerTypeChange}
          />
        </Form>
        <div>
          {/* <Button onClick={refreshData} style={{ width: 64, marginRight: 8 }}>
            重置
          </Button> */}
          <Button
            type="primary"
            htmlType="submit"
            onClick={getListData}
            style={{ width: 64 }}>
            查询
          </Button>
        </div>
      </div>
      <Spin spinning={loading}>
        <Chart
          option={yData.length ? option : { graphic }}
          ref={chartRef}
          notMerge={true}
          opts={{ useDirtyRect: true }}
          chartStyle={{ height: '350px' }}
        />
      </Spin>
    </Card>
  );
};

export default ChangeChart;
